package com.task.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.task.bean.TaskRegistBean;
import com.task.services.TaskRegistService;
import com.task.util.PageUtil;
import com.task.util.StringUtil;

@Controller
@RequestMapping(value="/taskRegist")
public class TaskRegistController {

	@Autowired
	private TaskRegistService taskRegistService;
	
	@RequestMapping(value="/list")
	public String registList() {
		return "regist-list";
	}
	
	@RequestMapping(value="/add")
	public String registAdd(HttpServletRequest request,String id) {
		TaskRegistBean bean=null;
		if(!StringUtil.isNUll(id) && !"-1".equals(id)) {
			bean=this.taskRegistService.getRegistBean(Integer.valueOf(id));
		}else {
			bean=new TaskRegistBean();
		}
		request.setAttribute("registBean", bean);
		return "regist-add";
	}
	
	@RequestMapping(value="/addRegistBean",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> addResit(@RequestBody TaskRegistBean bean) {
		if(StringUtil.isNUll(bean.getId())) {
			this.taskRegistService.saveRegist(bean);
		}else {
			this.taskRegistService.updateRegist(bean);
		}
		return StringUtil.returnSucess();
	}
	
	
	@ResponseBody
	@RequestMapping(value="/data")
	public Map<String,Object> getRegistData(@RequestBody Map<String,String> queryMap) throws JsonParseException, JsonMappingException, IOException{
		queryMap.putAll(PageUtil.getPage(queryMap.get("page"), queryMap.get("limit")));
		
		ObjectMapper mapper = new ObjectMapper(); 
		if(!StringUtil.isNUll(queryMap.get("search"))) {
			queryMap.putAll(mapper.readValue(queryMap.get("search"), Map.class));
			queryMap.remove("search");
		}
		
		List<TaskRegistBean> registList=this.taskRegistService.getAllTaskRegist(queryMap);
		
		Map<String,Object>resultMap=new HashMap<String,Object>();
		resultMap.put("code", "0");
		resultMap.put("msg", "");
		resultMap.put("page", queryMap.get("page"));
		resultMap.put("limit", queryMap.get("limit"));
		resultMap.put("count", this.taskRegistService.getRegistCount(queryMap));
		resultMap.put("data", registList);
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value="/del")
	public Map<String,Object> registdel(@RequestParam("ids") String ids) {
		this.taskRegistService.delRegist(ids);
		 return StringUtil.returnSucess();
	}
	
}
